import React from 'react';
import {createStore} from './../redux/redux';
import store from './../redux/reducers'
import {ADD_TODO,DEL_TODO} from './../redux/types'

// action creator
let addTodo = (text) => {
    return {type: ADD_TODO, text};
}
let delTodo = (index) => {// action creator
    return {type: DEL_TODO, index};
}

//3. 创建Todo组件
//4.连接store和Todo组件
class Todo extends React.Component {
    constructor() {
        super();
        //这时其实是实现了store的状态和本地状态的映射
        //仓库里状态很多，但是本组件可能只需很少一部分，那么只需要把自己需要的部分拿过来即可
        this.state = {list: store.getState().todo.list};
    }

    componentWillMount() {
        store.subscribe(() => {
            this.setState({list: store.getState().todo.list});
        });
    }
    handleKeyDown = (event)=>{
        //取得当前按下的键
        let keyCode = event.keyCode;
        if(keyCode === 13){
            //获取输入框的值
            let text = event.target.value;
            store.dispatch(addTodo(text));//向仓库派发一个action
            event.target.value = '';
        }
    }
    render() {
        return (
            <div>
                <input type="text" onKeyDown={this.handleKeyDown}/>
                <ul>
                    {
                        this.state.list.map((item,index)=>(
                            <li key={index}>{item} <button onClick={()=>store.dispatch(delTodo(index))}>x</button></li>
                        ))
                    }
                </ul>
            </div>
        )
    }
}
export default Todo


